/**
 * 角色页
 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import Modal from './modal';
import shouldComponentUpdate from '../../components/decorator/shouldComponentUpdate';
import Table from './table';
import Filter from './filter';

const styles = {
	table: {
	}
};

@shouldComponentUpdate
class SysRole extends React.Component {

	edit = t => {
		if (t && !t.id) return;
		const { dispatch } = this.props;
		dispatch({
			type: 'sysRole/edit',
			payload: t
		});
	}

	delete = t => {
		// 删除
		if (!t.id) return;
		const { dispatch } = this.props;
		dispatch({
			type: 'sysRole/delete',
			id: t.id,
			kind: 'sysRole',
		});
	}

	add = () => {
		// 新增一个角色
		const { dispatch } = this.props;
		dispatch({
			type: 'sysRole/edit',
			payload: {
				id: null,
				remark: '',
				roleName: '',
				shareBenefitType: 1
			}
		});
	}

	handleOk = t => {
		// 保存更改
		const { dispatch } = this.props;
		const action = {
			type: 'sysRole/create',
			payload: t
		};
		if (t.id) {
			action.type = 'sysRole/update';
		}
		dispatch(action);
	}

	permissionSelect = ids => {
		this.props.dispatch({
			type: 'sysRole/set',
			payload: {
				permissionIds: ids
			}
		});
	}

	nameValidator = (rule, value, callback) => {
		const { sysRole } = this.props;
		const { list, currentItem } = sysRole;
		const res = list.find(r => r.roleName === value && r.id !== currentItem.id);
		callback(res);
	}

	render() {
		const { sysRole, permissions = [], isAdmin, roles } = this.props;
		const {
			list, currentItem, permissionIds
		} = sysRole;

		// 不是admin隐藏版本权限
		let pList = [];
		if (isAdmin) pList = permissions;
		else pList = permissions.filter(v => v.permissionKey);

		return (
			<div className="content-inner">
				<Filter
					new={this.add}
				/>
				<Table
					list={list}
					edit={this.edit}
					delete={this.delete}
				/>
				<Modal
					data={currentItem}
					onOk={this.handleOk}
					isAdmin={isAdmin}
					handleCancel={() => this.edit(null)}
					permissionSelect={this.permissionSelect}
					permissionList={pList}
					permissionIds={permissionIds}
					nameValidator={this.nameValidator}
					roleDetail={roles[0]} // 判断当前用户角色权限，多角色的时候不适用了
				/>
			</div>
		);
	}
}

export default connect(
	({ sysRole, app, loading }) => ({ sysRole, permissions: app.user.permissions, isAdmin: app.user.isAdmin, loading, roles: app.user.roles })
)(SysRole);
